package com.ruoyi.common.core.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.WeChatConstants;
import com.ruoyi.common.core.domain.model.WeChatAuthorizeLoginUserInfoVo;
import com.ruoyi.common.core.domain.model.WeChatMiniAuthorizeVo;
import com.ruoyi.common.core.domain.model.WeChatOauthToken;
import com.ruoyi.common.exception.user.UserException;
import com.ruoyi.common.utils.RestTemplateUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @Description: 微信公用服务实现类
 * @Author: wk
 * @Date: 2022/7/27 15:04
 * @Version: 1.0
 */
@Service
@RequiredArgsConstructor
public class WechatNewServiceImpl implements WechatNewService{
    private final RestTemplateUtil restTemplateUtil;

    /**
     * 小程序ID
     **/
    @Value("${wx.appId}")
    private String appId;
    /**
     * 小程序密钥
     **/
    @Value("${wx.secret}")
    private String secret;


    /**
     * 获取开放平台access_token
     * 通过 code 获取
     * 公众号使用
     * @return 开放平台accessToken对象
     */
    @Override
    public WeChatOauthToken getOauth2AccessToken(String code) {
      return null;
    }

    @Override
    public WeChatAuthorizeLoginUserInfoVo getSnsUserInfo(String accessToken, String openid) {
        String url = StrUtil.format(WeChatConstants.WECHAT_SNS_USERINFO_URL, accessToken, openid, "zh_CN");
        String data = restTemplateUtil.getData(url);
        return JSONObject.parseObject(data, WeChatAuthorizeLoginUserInfoVo.class);
    }

    /**
     * 小程序登录凭证校验
     * @return 小程序登录校验对象
     */
    @Override
    public WeChatMiniAuthorizeVo miniAuthCode(String code) {
        String url = StrUtil.format(WeChatConstants.WECHAT_MINI_SNS_AUTH_CODE2SESSION_URL, appId, secret, code);
        String data = restTemplateUtil.getData(url);
        if (ObjectUtil.isNull(data)) {
            throw new UserException("微信平台接口异常，没任何数据返回！");
        }
        return JSONObject.parseObject(data, WeChatMiniAuthorizeVo.class);
    }
}
